<?php

namespace app\common;

/**
 * 验证
 */
abstract class Validate
{
    protected $request;

    public function __construct(\think\Request $request)
    {
        $this->request = $request;

        $validate = (new \think\Validate())->make($this->rules(), $this->message(), $this->field());
        $result = $validate->check($request->param());

        $path = $this->request->path();
        if (!$result) {
            if (ob_get_contents()) {
                @ob_clean();
            }
            header('Content-type:application/json;charset=utf-8');
            if (strpos($path, 'admin')) {
                $data = [
                    'meta' => [
                        'code' => _MSG_INVALID_CLIENT_PARAM,
                        'msg' => $validate->getError(),
                        'details' => $validate->getError(),
                        'status' => 'error'
                    ]
                ];
            } else {
                $data = ['code' => _MSG_INVALID_CLIENT_PARAM, 'msg' => $validate->getError(), 'data' => []];
            }
            echo json_encode($data, JSON_PARTIAL_OUTPUT_ON_ERROR | JSON_UNESCAPED_UNICODE);
            exit();
        }
    }

    public function rules()
    {
        return [];
    }

    public function message()
    {
        return [];
    }

    public function field()
    {
        return [];
    }

    public function param()
    {
        return $this->request->param();
    }

    public function post()
    {
        return $this->request->post();
    }

    public function get()
    {
        return $this->request->get();
    }
}
